# -*- coding: utf-8 -*-

import sys,os
import random,time,inspect

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext, Context, loader,Template
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.utils import translation
from django import forms
from django.core import serializers
from django.utils import simplejson

from models import *
import settings


""" Serialize helpers """
"""
def SerializeMany(queryset, root_name=None, extra={} ):
    if not root_name:
        root_name = queryset.model._meta.verbose_name_plural
    return '{"total": %s,"%s": %s}' % (queryset.count(), root_name, serializers.serialize('json', queryset))

def SerializeOne(obj, root_name=None):
    if not root_name:
        root_name = 'object'
    return '{"total": 1, "%s": %s}' % (root_name, serializers.serialize('json', [obj]))
"""

""" Model helpers """
"""
def get_fields(modelcls,fieldtype='list'):
    # Get the fields from Model.EXT attribute
    fields=[]
    if 'EXT' in dir(modelcls):
        if 'fields_'+fieldtype in dir(modelcls.EXT):
            fields=getattr(modelcls.EXT,'fields_'+fieldtype)
    return fields

def get_field_listing(modelcls,include_fields=[]):
    fields=[]
    for f in modelcls._meta.fields:
        if f.name!='id':
            if f.name in include_fields or len(include_fields)==0:
                if str(f.get_internal_type())=='ForeignKey':
                    related=f.related.name
                    #print dir(f)
                    #print f.get_flatchoices()
                    #print dir(f.related)
                    #print f.related.model.objects.all()
                else:
                    related=''
                ft=[f.name, 'fields.'+f.name, f.get_internal_type(), f.verbose_name, related, f.editable, f.blank]
                #print ft
                fields.append(ft)
    return fields

def get_related_lists(modelcls):
    # return all data related to a given model
    # used for dropdowns
    #print 'get_related_lists'
    related={}
    for f in modelcls._meta.fields:
        if str(f.get_internal_type())=='ForeignKey':
            #related=f.related.name
            name=f.related.parent_model.__name__
            #print f.related.parent_model.__name__
            #print dir(f.related)
            data=[]
            for o in f.related.parent_model.objects.all():
                data.append( (o.id,str(o)) )
            related[f.name]=data
            #related['fields.'+f.name]=data
    return related

def get_ext_setting(modelcls,key,default=False):
    if 'EXT' in modelcls.__dict__:
        if modelcls.EXT.__dict__:
            if key in modelcls.EXT.__dict__:
                return modelcls.EXT.__dict__[key]
    return default
"""

""" Test View """

def test(request):
    #c={'obj':Menu.objects.all()[0]}
    #PreRenderSignal.send(sender=None,context=c,view=test)
    #r=render_to_response('test.html',RequestContext(request,c))
    return HttpResponse('42')


""" List view """
"""
def view_list(request,model):
    c={}
    c['model']=model

    modelcls=getattr(sys.modules[__name__],model)
    list_fieldnames=get_fields(modelcls,'list')
    edit_fieldnames=get_fields(modelcls,'edit')

    c['description']=get_ext_setting(modelcls,'description','')
    c['rights']=get_ext_setting(modelcls, 'rights', {'edit':True, 'add':True, 'delete':True })

    c['list_fields']=[('pk','pk','AutoField','ID')]
    c['list_fields'].extend(get_field_listing(modelcls,list_fieldnames))

    c['edit_fields']=[('pk','pk','AutoField','ID')]
    c['edit_fields'].extend(get_field_listing(modelcls,edit_fieldnames))

    print request.GET
    for k,v in request.GET.items():
        print k,v

    related=get_related_lists(modelcls)
    c['related']={}
    for k in related.keys():
        c['related'][k]=related[k]

    c['object_actions']= get_ext_setting(modelcls,'object_actions',[])

    r=render_to_response('view_list.html',RequestContext(request,c))
    return r


def json_list(request,model):
    modelcls=getattr(sys.modules[__name__],model)
    e={}

    # Get all the objects from model and apply sort
    if 'sort' in request.POST:
        s=request.POST['sort']
        if request.POST.get('dir','ASC')!='ASC': s='-'+s
        q=modelcls.objects.all().order_by(s)
    else:
        q=modelcls.objects.all()

    #    filter_by = { '%s__%s' % (request.POST['name'], 'istartswith') : request.GET['query'] }
    #    q=modelcls.objects.all().filter(**filter_by)


    if 'pk' in request.GET:
        # If a specific pk i supplied, then only return
        # that object
        q=[q.get(pk=request.GET['pk'])]
        e['total']=1
    else:
        # Otherwise count the record in the query
        e['total']=q.count()

    # Handle pagination, if used
    if 'start' in request.POST and 'limit' in request.POST:
        p1=int(request.POST['start'])
        p2=int(request.POST['limit'])+p1
        q=q[p1:p2]

    # Resulting record count after pagination
    e['recordsReturned']=len(q)

    # Insert the recordlist into the final JSon reply
    e['results']='%results%' # serializers.serialize('json', q)
    c=simplejson.dumps(e).replace('"%results%"',serializers.serialize('json', q))

    return HttpResponse(c)

def rest_save(request,model):
    modelcls=getattr(sys.modules[__name__],model)
    pk=request.POST['pk']
    if pk=='':
        # Its a new object
        q=modelcls()
    else:
        # Its an existing object
        q=modelcls.objects.get(pk=pk)
    for f in modelcls._meta.fields:
        if f.name!='id':
            if f.name in request.POST:
                v=request.POST[f.name]
                print f.name,f.get_internal_type(),v
                if f.get_internal_type()!='ForeignKey':
                    if f.get_internal_type() in ['DateField','DateTimeField']:
                        if v=='':
                            v=None
                    if v:
                        try:
                            print ' ',f.name,'=',v
                            setattr(q,f.name,v)
                        except:
                            print 'Error, count not set field',f.name,'to value',v
                else:
                    # save foreignkey
                    #print dir(f)
                    #print f.related
                    #print f.name
                    ro=f.related.parent_model.objects.get(pk=int(v))
                    setattr(q,f.name,ro)
    q.save()

    r={'success':True, 'msg':'Ok!'}
    return HttpResponse(simplejson.dumps(r))



def rest_delete(request,model,id):
    model=getattr(sys.modules[__name__],model)
    o=model.objects.get(pk=id)
    o.delete()
    return HttpResponse("OK")
"""

""" Tree view """
"""
def view_tree(request,model):
    c={}
    c['model']=model
    #c['fields']=[('pk','AutoField'),('fields.cdate',''),('fields.name','')]
    c['fields']=[('pk','AutoField','ID')]

    model=getattr(sys.modules[__name__],model)
    for f in model._meta.fields:
        if f.name!='id':
            ft='fields.'+f.name,f.get_internal_type(),f.verbose_name
            print ft
            c['fields'].append(ft)

    r=render_to_response('view_tree.html',RequestContext(request,c))
    return r


def json_tree(request,model):
    model=getattr(sys.modules[__name__],model)
    q=model.objects.all()
    return HttpResponse(SerializeMany(q, root_name='results'), mimetype='text/javascript')
"""
